package com.video.controller.system;

import com.video.commons.loginaop.NoMustLogin;
import com.video.commons.runtimelog.RunLogUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * logo管理的controller
 */
@Controller
@RequestMapping("/logo")
public class LogoController {

    @Value("${upload.logopath}")
    private String logoPath;

    /**
     * logo管理
     * @return
     */
    @NoMustLogin
    @RequestMapping("/manager")
    public String logoManager(){
        return "system/logomanager";
    }

    /**
     * 上传logo
     * @return
     */
    @NoMustLogin
    @RequestMapping("/upload")
    public String uploadLogo(MultipartFile file) throws IOException {
        RunLogUtil.info("上传logo [ upload logo ]：" + file.getOriginalFilename());
//        String path = LogoController.class.getResource("/static").getPath() + "/logo/logo.png";
//        String path = LogoController.class.getResource("/static").getPath() + "/logo/logo.png";

        File f = new File(logoPath);
        if (!f.exists()){
            f.mkdirs();
        }

        String path = logoPath + "/logo.png";

        RunLogUtil.info("上传logo [ upload logo ] 上传路径为: " + path);

        try (
                InputStream in = file.getInputStream();
                OutputStream out = new FileOutputStream(path);
        ){

            IOUtils.copy(in, out);

        }

        return "redirect:/logo/manager";
    }

    /**
     * 获取logo
     */
    @NoMustLogin
    @RequestMapping("/getlogo")
    @ResponseBody
    public void getLogo(HttpServletResponse response){

        String path = logoPath + "/logo.png";
        File file = new File(path);
        //存在
        try (
                InputStream in = new FileInputStream(path);
                ServletOutputStream out = response.getOutputStream();
        ){
            if (file.exists()){
                IOUtils.copy(in, out);
            } else {
                out.print(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
